package com.auotc.demo

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private lateinit var framents: MutableList<Fragment>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initFragment()
    }

    private fun initFragment() {
        framents = mutableListOf(
                HomeFragment(),
                HotFragment(),
                CategoryFragment(),
                CartFragment(),
                MineFragment()
        )
        main_radio_group.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rb_main_home -> {
                    changeFragment(currentFragment, HomeFragment())
                }
                R.id.rb_main_hot -> {
                    changeFragment(currentFragment, HotFragment())
                }
                R.id.rb_main_category -> {
                    changeFragment(currentFragment, framents[2])
                }
                R.id.rb_main_cart -> {
                    changeFragment(currentFragment, framents[3])
                }
                R.id.rb_main_mine -> {
                    changeFragment(currentFragment, framents[4])
                }
            }
        }
        rb_main_home.isChecked = true
    }

    private var currentFragment: Fragment? = null
    /**
     * @param from 当前显示的Fragment, 即将被隐藏
     * @param to   将要切换到的Fragment，即将要显示
     */
    private fun changeFragment(from: Fragment?, to: Fragment?) {
        val ft = supportFragmentManager.beginTransaction()
        if (from == to || null == to) return
        currentFragment = to
        if (null != from) ft.hide(from)
        if (to.isAdded) ft.show(to).commit()
        else ft.add(R.id.fl_content_main, to).commit()
    }
}
